const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  console.log('getActivities 云函数被调用，参数：', event)
  
  try {
    const { 
      category = 'all',  // 活动分类
      limit = 20,        // 每页数量
      skip = 0,          // 跳过数量
      orderBy = 'createdAt', // 排序字段
      orderType = 'desc'     // 排序方式
    } = event

    const activitiesCollection = db.collection('activities')
    
    // 构建查询条件
    let query = activitiesCollection
    
    // 如果指定了分类且不是'all'，则按type字段筛选
    if (category && category !== 'all') {
      query = query.where({
        type: category
      })
    }
    
    // 添加排序、分页
    const result = await query
      .orderBy(orderBy, orderType)
      .skip(skip)
      .limit(limit)
      .get()
    
    console.log(`查询到 ${result.data.length} 个活动`)
    
    return {
      success: true,
      data: result.data,
      total: result.data.length,
      hasMore: result.data.length === limit, // 简单判断是否还有更多数据
      message: '活动列表获取成功'
    }
    
  } catch (error) {
    console.error('获取活动列表失败:', error)
    return {
      success: false,
      error: error.message,
      message: '获取活动列表失败'
    }
  }
}